import area from 'areaJSON';

class $area {
	constructor() {
		this.version = '1.00.00'
		this.self = () => getCurrentPages()[getCurrentPages().length - 1]
		this.JSON = area
	}

	setData(p = 0, c = 0, d = 0) {

		let This = this.self()

		this.p = p
		this.c = c
		this.d = d
		// 设置省的数据
		var province = area['100000']
		var provinceName = [];
		var provinceCode = [];
		for(var item in province) {
			provinceName.push(province[item])
			provinceCode.push(item)
		}
		This.setData({
			provinceName: provinceName,
			provinceCode: provinceCode
		})
		// 设置市的数据
		var city = area[provinceCode[p]]
		var cityName = [];
		var cityCode = [];
		for(var item in city) {
			cityName.push(city[item])
			cityCode.push(item)
		}
		This.setData({
			cityName: cityName,
			cityCode: cityCode
		})
		// 设置区的数据
		var district = area[cityCode[c]]
		var districtName = [];
		var districtCode = [];
		if(!district){
			district = {}
			district[parseInt(cityCode[c]) + 1] = "市辖区"
		}
		for(var item in district) {
			districtName.push(district[item])
			districtCode.push(item)
		}
		This.setData({
			districtName: districtName,
			districtCode: districtCode
		})
	}

	sureData() {
		let This = this.self()
		This.setData({
			provinceSelIndex: this.p,
			citySelIndex: this.c,
			districtSelIndex: this.d
		})
		This.distpickerCancel()
	}

	getData() {
		let This = this.self()
		let data = This.data
		return {
			province: data.provinceName[data.provinceSelIndex] || "",
			provinceCode: data.provinceCode[data.provinceSelIndex] || "",
			city: data.cityName[data.citySelIndex] || "",
			cityCode: data.cityCode[data.citySelIndex] || "",
			district: data.districtName[data.districtSelIndex] || "",
			districtCode: data.districtCode[data.districtSelIndex] || "",
		}
	}

	getString(districtCode, city = "", district = "") {
		let provinc = ""
		if(/.*[\u4e00-\u9fa5]+.*$/.test(districtCode)) {
			provinc = districtCode
		} else if(districtCode && districtCode != "000000") {
			let dCode = (districtCode).toString()
			let provinceCode = dCode.substring(0, 2) + "0000"
			let cityCode = dCode.substring(0, 4) + "00"
			provinc = this.JSON["100000"][provinceCode] || ""
			if(provinceCode == "810000" || provinceCode == "820000") cityCode = dCode.substring(0, 2) + "0100"
			city = this.JSON[provinceCode][cityCode] || ""
			district = this.JSON[cityCode]? this.JSON[cityCode][districtCode]: ""
		}
		if(city.indexOf(provinc) > -1) {
			city = ""
		}
		return provinc? (provinc + city + (district || "市辖区")) : "请设置所在地区"
	}

	change(e) {
		let val = e.detail.value
		this.setData(val[0], val[1], val[2])
	}

	show() {
		let This = this.self()
		This.setData({
			showDistpicker: true
		})
	}

	hide() {
		let This = this.self()
		This.setData({
			showDistpicker: false
		})
	}
}

export default new $area()